﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;

namespace MMM.Services.Expansion
{
    public class InputExcelDataClass
    {
        /// <summary>
        /// 检测数据表的表结构
        /// </summary>
        /// <param name="excelHead"></param>
        /// <param name="filePath"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        public static Dictionary<string, int> CheckExcelHead(string excelHead, string filePath, out int rowIndex, out string msgs)
        {
            msgs = "";
            Dictionary<string, int> dic = new Dictionary<string, int>();
            List<string> headList = new List<string>();
            string[] heads = excelHead.Split('|');
            headList.AddRange(heads);
            rowIndex = 0;
            string fileExtions = Path.GetExtension(filePath);
            if (fileExtions == ".xls" || fileExtions == ".xlsx")
            {
                string fullPath = HttpContext.Current.Server.MapPath(filePath);
                using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read))//将xls文件的信息保存在文件流中
                {
                    HSSFWorkbook workbook = new HSSFWorkbook(fs);

                    ISheet sheet = workbook.GetSheetAt(0);
                    if (sheet.LastRowNum > 0)
                    {

                        for (int i = 0; i < sheet.LastRowNum; i++)
                        {
                            if (msgs.Length > 0)
                            {
                                break;
                            }
                            IRow row = sheet.GetRow(i);
                            for (int j = 0; j < row.LastCellNum; j++)
                            {
                                string sss = row.GetCell(j).StringCellValue;
                                if (!string.IsNullOrEmpty(sss))
                                {
                                    if (headList.Contains(sss))
                                    {
                                        dic.Add(sss, j);
                                        rowIndex = i;
                                    }
                                }
                            }

                            for (int k = 0; k < heads.Length; k++)
                            {
                                if (!dic.ContainsKey(heads[k]))
                                {
                                    msgs += "‘" + heads[k] + "’";
                                }
                            }
                        }

                    }
                }
            }

            return dic;
        }
    }
}
